package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.OrderDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderDetailService orderDetailService ;

    @Autowired
    private ShoppingCartService shoppingCartService ;
    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    @Cacheable(value = "list.order",key = "#page+'-'+#pageSize+'-'+#number+#beginTime+#endTime",cacheManager = "cacheManagerHour")
    public R<Page> page(int page, int pageSize,Long number,String beginTime,String endTime){

        log.info("开始时间："+beginTime);
        log.info("结束时间："+endTime);
        //分页构造器
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        if(!(number == null || "".equals(number))){
            queryWrapper.eq(Orders::getNumber,number);
        }
        if(!StringUtils.isEmpty(beginTime)) {
            queryWrapper.ge(Orders::getCheckoutTime,beginTime);
            queryWrapper.le(Orders::getCheckoutTime,endTime);
        }
        //添加排序条件，根据sort进行排序
        //queryWrapper.orderByAsc(Orders::getSort);

        //分页查询
        orderService.page(pageInfo,queryWrapper);

        return R.success(pageInfo);
    }
    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")

    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据：{}",orders);
        Long id = BaseContext.getCurrentId();
        User user = userService.getById(id);
        orders.setUserName(user.getName());
        orderService.submit(orders);
        return R.success("下单成功");
    }


//用户端订单
    @GetMapping("/userPage")
    public R<Page>  userPage(int page, int pageSize){
        //分页构造器
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        queryWrapper.orderByDesc(Orders::getCheckoutTime) ;
        orderService.page(pageInfo,queryWrapper);

        //根据订单id获取订单详情和菜品的信息


//        long total = pageInfo.getTotal();
        List<Orders> records = pageInfo.getRecords();

        List<Orders> orders = new ArrayList<>();
        records.stream().forEach(item->{
            Long id = item.getId();
            LambdaQueryWrapper<OrderDetail> queryWrapperDt = new LambdaQueryWrapper<>() ;
            queryWrapperDt.eq(OrderDetail::getOrderId,id);
            OrderDto orderDto = new OrderDto() ;
            List<OrderDetail> list = orderDetailService.list(queryWrapperDt);
            BeanUtils.copyProperties(item,orderDto);
            orderDto.setOrderDetails(list);
            orders.add(orderDto) ;
        });

        pageInfo.setRecords(orders);
        return R.success(pageInfo);
    }

    @PutMapping
    @CacheEvict(value = "list.order",allEntries = true)//清空缓存
    public R<String> update(@RequestBody Orders orders){
//        Integer status = null ;
//        status = orders.getStatus();
//        if(status==2){
//            orders.setStatus(3);
//        }else if(status==3){
//            orders.setStatus(4);
//        }
        orderService.updateById(orders);
        return R.success("修改订单成功");
    }

//    将购买订单信息加入购物车
    @PostMapping("/again")
    public R<String> again(@RequestBody String id){
        LambdaQueryWrapper<OrderDetail> queryWrapper  = new LambdaQueryWrapper<>() ;
        queryWrapper.eq(OrderDetail::getOrderId,id);
        List<OrderDetail> list = orderDetailService.list(queryWrapper);

        Long userId = BaseContext.getCurrentId();

        List<ShoppingCart> listCar = new ArrayList<>() ;

        LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ShoppingCart::getUserId,userId);

        List<ShoppingCart> listCarOld = shoppingCartService.list(lambdaQueryWrapper);

        Map<Long, ShoppingCart> collect = listCarOld.stream().collect(Collectors.toMap(ShoppingCart::getDishId, v -> v));


        list.stream().forEach(item->{
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userId);
            BeanUtils.copyProperties(item,shoppingCart);
            ShoppingCart cart = collect.get(item.getDishId());
            if(cart==null||"".equals(cart)){
                listCar.add(shoppingCart) ;
            }else{
//                修改数量
                Integer num = cart.getNumber();
                cart.setNumber(num+item.getNumber());
                shoppingCartService.updateById(cart);
            }

        });

        shoppingCartService.saveBatch(listCar);
        return R.success("添加购物车成功");
    }

}